import { useStore } from 'vuex'

/** 初始化字体
 * @param {string[]} fonts 字体名称列表
 */
export const initFontFamily = (fonts) => {
	const vk = uni.vk;
	const store = useStore()
	const loadedFonts = store.state.$app.fonts;
	const {baseUrl} = store.state.$app.config.staticUrl;
	// #ifdef MP-WEIXIN
	fonts.forEach((font) => {
		if (!loadedFonts.includes(font)) {
			uni.loadFontFace({
				global: true,
				family: font,
				source: `url("${baseUrl}/avatar-client/font/${font}.ttf")`,
				success: () => {
					console.log(`加载字体${font}成功`);
					vk.vuex.set('$app.fonts', [...loadedFonts, font]);
				},
				fail(e) {
					console.log('加载字体失败', e, `"https://mp-6311ccac-218f-4072-bf34-9cd284ea3029.cdn.bspapp.com/avatar-client/font/${font}.ttf"`);
				},
				scopes: ["webview", "native"],
			})
		}
	})
	// #endif
}

/** 初始化模板参数 */
const templateDataInit = (pages) => {
	const vk = uni.vk;
	return new Promise((resolve, reject) => {
		const page = pages[pages.length - 1];
		const eventChannel = page.getOpenerEventChannel();
		eventChannel.on('acceptDataFromOpenerPage', (data) => {
			if (data) {
				const { previewUrl } = data;
				if (typeof previewUrl === 'string') {
					data.previewUrl = [previewUrl]
				}
				resolve(data);
			} else {
				reject()
			}
		})
	})
}

const pageInit = async (option, fonts = ['qinzi']) => {
	const vk = uni.vk;
	console.log('onLoad:', option);
	initFontFamily(fonts);
	const { i, t, scene } = option;
	let templateId = t;
	let inviteCode = i;
	if (scene) {
		const queryStr = decodeURIComponent(scene);
		queryStr.split('&').forEach((item) => {
			const [key, value] = item.split('=');
			if (key === 't' && value) {
				templateId = value;
			}
			if (key === 'i' && value) {
				inviteCode = value
			}
		})
	}
	console.log('init templateId:', templateId);
	console.log('init inviteCode:', i);
	const pages = getCurrentPages();
	const path = `/${pages[pages.length - 1].route}`;
	console.log('当前页面：', path);
	let templateData = null;
	if (!templateId) {
		let data = {};
		try {
			data = await templateDataInit(pages);
			templateData = data[path] || null;
		} catch(err){
			// pass
		}
	}

	if (templateId && !templateData) {
		let res = null;
		try {
			res = await vk.callFunction({
				url: 'client/template/pub/getTemplate',
				title: '请求中...',
				data: {
					templateId
				},
			});
			if (res) {
				templateData = res;
			}
		} catch (error) {
			vk.toast('查询失败,请稍后再试!');
		}
	}
	return { templateData, inviteCode };
}

const shareInit = (templateData) => {
	const vk = uni.vk;
	console.log('shareInit templateData', templateData);
	const userInfo = vk.vuex.get('$user.userInfo');
	const inviteCode = userInfo.my_invite_code;
	const pages = getCurrentPages();
	const path = `/${pages[pages.length - 1].route}?t=${templateData.template_id}&i=${inviteCode}`;
	let imageUrl = templateData.previewUrl ? templateData.previewUrl[0] : '/static/logo.png'
	const title = templateData.shareText || '专属头像在线制作，快来试一试!';
	const shareMessage = {
		title,
		path,
		imageUrl,
	};
	console.log('share message:', shareMessage);
	return shareMessage;
}

export default {
	pageInit,
	shareInit
}
